<template>
  <div class="common_block_div" v-loading="loading">
    <!-- 标题栏 -->
    <div class="common_page_tt flex_ac margin_b20">
      <a href="javascript:;" @click="$router.go(-1)">
        <img src="@/assets/pinggu/back.png" alt="">
      </a>
      <span class="margin_l10">{{ form.title || '模板详情' }}</span>
    </div>

    <!-- 基本设置 -->
    <div class="form_section margin_b30">
      <div class="section_title margin_b20">基本设置</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <FormItem 
              label="项目标题" 
              class="" 
              type="input" 
              :form="form" 
              prop="title" 
              clearable 
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目开始时间" prop="begin_time">
              <el-date-picker
                v-model="form.begin_time"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择项目开始时间"
                style="width: 100%"
                clearable
                :picker-options="{
                  disabledDate: (time) => {
                    if (form.end_time) {
                      return time.getTime() > new Date(form.end_time).getTime();
                    }
                    return false;
                  }
                }"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目结束时间" prop="end_time">
              <el-date-picker
                v-model="form.end_time"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择项目结束时间"
                style="width: 100%"
                clearable
                :picker-options="{
                  disabledDate: (time) => {
                    if (form.begin_time) {
                      return time.getTime() < new Date(form.begin_time).getTime();
                    }
                    return false;
                  }
                }"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评委打分开始时间" prop="pw_df_begin_time">
              <el-date-picker
                v-model="form.pw_df_begin_time"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择评委打分开始时间"
                style="width: 100%"
                clearable
                :picker-options="{
                  disabledDate: (time) => {
                    if (form.pw_df_end_time) {
                      return time.getTime() > new Date(form.pw_df_end_time).getTime();
                    }
                    return false;
                  }
                }"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评委打分结束时间" prop="pw_df_end_time">
              <el-date-picker
                v-model="form.pw_df_end_time"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择评委打分结束时间"
                style="width: 100%"
                clearable
                :picker-options="{
                  disabledDate: (time) => {
                    if (form.pw_df_begin_time) {
                      return time.getTime() < new Date(form.pw_df_begin_time).getTime();
                    }
                    return false;
                  }
                }"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 规则设置 -->
    <div class="form_section margin_b30">
      <div class="section_title margin_b20">规则设置</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="题库模板" prop="question_template_id">
              <div class="flex_ac">
                <el-select 
                  v-model="form.question_template_id" 
                  placeholder="请选择题库模板" 
                  clearable 
                  filterable
                  style="flex: 1;"
                >
                  <el-option
                    v-for="item in questionTemplateOptions"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-button type="text" @click="handleGoToTemplate">去设置</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="基础权重分" prop="base_weight">
              <el-input-number 
                v-model="form.base_weight" 
                :min="0" 
                :max="100" 
                :step="1" 
                :precision="0"
                placeholder="请输入基础权重分" 
                style="width: 100%"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="评委权重分" prop="judge_weight">
              <el-input-number 
                v-model="form.judge_weight" 
                :min="0" 
                :max="100" 
                :step="1" 
                :precision="0"
                placeholder="请输入评委权重分" 
                style="width: 100%"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 附件 -->
    <div class="form_section margin_b30">
      <div class="section_title margin_b20">附件</div>
      <div class="attachment_list margin_b20">
        <div 
          v-for="(file, index) in attachmentList" 
          :key="index" 
          class="attachment_item flex_ac margin_b10"
        >
          <i 
            :class="getFileIcon(file.file_name)" 
            class="file_icon margin_r10"
            :style="{color: getFileIconColor(file.file_name)}"
          ></i>
          <span class="file_name flex1" :title="file.file_name">{{ file.file_name }}</span>
          <span class="file_size margin_r10">{{ formatFileSize(file.file_size) }}</span>
          <el-progress 
            v-if="file.uploading" 
            :percentage="file.uploadProgress || 0" 
            :status="file.uploadStatus"
            style="width: 200px; margin-right: 10px;"
          ></el-progress>
          <i 
            v-if="file.uploading" 
            class="el-icon-close margin_l10" 
            style="cursor: pointer; color: #F56C6C;"
            @click="cancelUpload(index)"
          ></i>
          <i 
            v-else
            class="el-icon-delete margin_l10" 
            style="cursor: pointer; color: #F56C6C;"
            @click="removeAttachment(index)"
          ></i>
        </div>
      </div>
      <el-upload
        ref="upload"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :on-success="handleUploadSuccess"
        :on-progress="handleUploadProgress"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        :file-list="fileList"
        :auto-upload="true"
        :show-file-list="false"
        accept=".pdf,.doc,.docx,.xls,.xlsx"
      >
        <el-button type="primary" icon="el-icon-upload">
          上传附件
        </el-button>
      </el-upload>
    </div>

    <!-- 项目描述 -->
    <div class="form_section margin_b30">
      <div class="section_title margin_b20">项目描述</div>
      <Editor 
        v-model="form.description" 
        :height="400"
        :min-height="300"
        :upload-url="editorUploadUrl"
      />
    </div>

    <!-- 底部操作按钮 -->
    <div class="bottom_actions margin_t30">
      <el-button type="primary" @click="handleSave" :loading="is_ajax">保存</el-button>
    </div>
  </div>
</template>

<script>
import Editor from "@/components/Editor/index.vue";
import FormItem from "@/components/FormItem/index.vue";
// 导入项目管理API
import projectApi from '@/api/project';
// 导入题库管理API
import questionBankApi from '@/api/questionBank';

export default {
  name: 'project_edit',
  components: {
    Editor,
    FormItem
  },
  data() {
    return {
      loading: false,
      is_ajax: false,
      id: '',
      form: {
        id: '',
        title: '',
        begin_time: '',
        end_time: '',
        pw_df_begin_time: '',
        pw_df_end_time: '',
        base_score_rate: '',
        pw_score_rate: '',
        q_id: '',
        content: '',
        kouling: '',
        submit_time: '',
        judge_time: '',
        question_template_id: '',
        base_weight: null,
        judge_weight: null,
        description: ''
      },
      rules: {
        title: [
          { required: true, message: "项目标题不能为空", trigger: "blur" }
        ],
        begin_time: [
          { required: true, message: "项目开始时间不能为空", trigger: "change" },
          { 
            validator: (rule, value, callback) => {
              if (value && this.form.end_time && new Date(value) > new Date(this.form.end_time)) {
                callback(new Error('项目开始时间不能大于结束时间'));
              } else {
                callback();
              }
            }, 
            trigger: "change" 
          }
        ],
        end_time: [
          { required: true, message: "项目结束时间不能为空", trigger: "change" },
          { 
            validator: (rule, value, callback) => {
              if (value && this.form.begin_time && new Date(value) < new Date(this.form.begin_time)) {
                callback(new Error('项目结束时间不能小于开始时间'));
              } else {
                callback();
              }
            }, 
            trigger: "change" 
          }
        ],
        pw_df_begin_time: [
          { required: true, message: "评委打分开始时间不能为空", trigger: "change" },
          { 
            validator: (rule, value, callback) => {
              if (value && this.form.pw_df_end_time && new Date(value) > new Date(this.form.pw_df_end_time)) {
                callback(new Error('评委打分开始时间不能大于结束时间'));
              } else {
                callback();
              }
            }, 
            trigger: "change" 
          }
        ],
        pw_df_end_time: [
          { required: true, message: "评委打分结束时间不能为空", trigger: "change" },
          { 
            validator: (rule, value, callback) => {
              if (value && this.form.pw_df_begin_time && new Date(value) < new Date(this.form.pw_df_begin_time)) {
                callback(new Error('评委打分结束时间不能小于开始时间'));
              } else {
                callback();
              }
            }, 
            trigger: "change" 
          }
        ],
        question_template_id: [
          { required: true, message: "题库模板不能为空", trigger: "change" }
        ],
        base_weight: [
          { required: true, message: "基础权重分不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              const baseRate = Number(value) || 0;
              const judgeRate = Number(this.form.judge_weight) || 0;
              if (baseRate + judgeRate > 100) {
                callback(new Error('基础权重分和评委权重分之和不能大于100'));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
        judge_weight: [
          { required: true, message: "评委权重分不能为空", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              const baseRate = Number(this.form.base_weight) || 0;
              const judgeRate = Number(value) || 0;
              if (baseRate + judgeRate > 100) {
                callback(new Error('基础权重分和评委权重分之和不能大于100'));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ]
      },
      questionTemplateOptions: [
        { id: '1', title: '2025精品项目题库模板' }
      ],
      weightOptions: [
        { value: '10', label: '10%' },
        { value: '20', label: '20%' },
        { value: '30', label: '30%' },
        { value: '40', label: '40%' },
        { value: '50', label: '50%' },
        { value: '60', label: '60%' },
        { value: '70', label: '70%' },
        { value: '80', label: '80%' },
        { value: '90', label: '90%' },
        { value: '100', label: '100%' }
      ],
      attachmentList: [],
      fileList: [],
      uploadUrl: this.http + '/manage/Attachment/upload',
      editorUploadUrl: '/api/Upload/image',
      uploadHeaders: {
        'user-authorization': this.getState().token,
      }
    }
  },
  created() {
    this.id = this.$route.query.id || '';
    // 获取基础数据
    this.getBaseData();
    if (this.id) {
      this.getData();
    }
  },
  methods: {
    /** 跳转到设置模版 */
    handleGoToTemplate() {
      this.$router.push({
        path: '/answer/addanswer'
      });
    },
    /** 获取项目详情 */
    getData() {
      const _this = this;
      if (!this.id) {
        this.loading = false;
        return;
      }
      
      this.loading = true;
      // 使用项目API获取详情
      projectApi.detail({id: this.id}).then(function(res) {
        if (res && res.data) {
          const data = res.data;
          // 填充表单数据
          _this.form = {
            id: data.id || '',
            title: data.title || '',
            begin_time: data.begin_time || '',
            end_time: data.end_time || '',
            pw_df_begin_time: data.pw_df_begin_time || '',
            pw_df_end_time: data.pw_df_end_time || '',
            base_score_rate: data.base_score_rate || '',
            pw_score_rate: data.pw_score_rate || '',
            q_id: data.q_id || '',
            content: data.content || '',
            kouling: data.kouling || '',
            // 兼容旧字段名
            submit_time: data.submit_time || data.begin_time || '',
            judge_time: data.judge_time || data.pw_df_begin_time || '',
            question_template_id: data.question_template_id || data.q_id || '',
            base_weight: data.base_weight !== null && data.base_weight !== undefined ? Number(data.base_weight) : (data.base_score_rate !== null && data.base_score_rate !== undefined ? Number(data.base_score_rate) : null),
            judge_weight: data.judge_weight !== null && data.judge_weight !== undefined ? Number(data.judge_weight) : (data.pw_score_rate !== null && data.pw_score_rate !== undefined ? Number(data.pw_score_rate) : null),
            description: data.description || data.content || ''
          };
          
          // 处理附件列表
          if (data.arrr_data_detail && data.arrr_data_detail.length > 0) {
            _this.attachmentList = data.arrr_data_detail.map(item => ({
              id: item.id,
              file_name: item.file_name,
              file_url: item.file_url,
              file_size: item.file_size || 0,
              uploading: false
            }));
          } else if (data.attachments && data.attachments.length > 0) {
            // 兼容其他附件字段名
            _this.attachmentList = data.attachments.map(item => ({
              id: item.id || item.attachment_id,
              file_name: item.file_name,
              file_url: item.file_url,
              file_size: item.file_size || 0,
              uploading: false
            }));
          } else {
            _this.attachmentList = [];
          }
        }
        _this.loading = false;
      }).catch(function(error) {
        console.error('获取项目详情失败:', error);
        _this.$message.error('获取项目详情失败');
        _this.loading = false;
      });
    },
    
    /** 获取基础数据 */
    getBaseData() {
      const _this = this;
      projectApi.getBaseData().then(function(res) {
        if(res && res.data){
          const data = res.data;
          // 处理题库模板选项
          if(data.questionnaire_version_options){
            const templates = data.questionnaire_version_options || [];
            _this.questionTemplateOptions = templates.map(item => ({
              id: item.id,
              title: item.title || item.name
            }));
          }
          // 如果有其他基础数据，可以在这里处理
          // 例如：权重选项、状态选项等
        }
      }).catch(function(error) {
        console.error('获取基础数据失败:', error);
        // 如果获取基础数据失败，尝试使用备用方法获取题库模板
        _this.getQuestionTemplates();
      });
    },
    
    /** 获取题库模板列表（备用方法） */
    getQuestionTemplates() {
      const _this = this;
      questionBankApi.templateList({limit: 9999}).then(function(res) {
        if(res && res.message && res.message.data){
          _this.questionTemplateOptions = res.message.data.map(item => ({
            id: item.id,
            title: item.title || item.name
          }));
        }
      }).catch(function(error) {
        console.error('获取题库模板列表失败:', error);
      });
    },
    handleUploadSuccess(res, file, fileList) {
      if (res.status == 200) {
        // 找到正在上传的文件并更新
        const uploadingIndex = this.attachmentList.findIndex(item => item.uploading && item.file_name === file.name);
        if (uploadingIndex !== -1) {
          this.$set(this.attachmentList[uploadingIndex], 'id', res.data.attachment_id);
          this.$set(this.attachmentList[uploadingIndex], 'file_url', res.data.file_url);
          this.$set(this.attachmentList[uploadingIndex], 'uploading', false);
          this.$set(this.attachmentList[uploadingIndex], 'uploadProgress', 100);
          this.$set(this.attachmentList[uploadingIndex], 'uploadStatus', 'success');
        } else {
          const attachment = {
            id: res.data.attachment_id,
            file_name: file.name,
            file_size: file.size,
            file_url: res.data.file_url,
            uploading: false
          };
          this.attachmentList.push(attachment);
        }
        this.$message.success('上传成功');
      } else {
        this.$message.error(res.message || '上传失败');
        // 移除上传失败的文件
        const uploadingIndex = this.attachmentList.findIndex(item => item.uploading && item.file_name === file.name);
        if (uploadingIndex !== -1) {
          this.attachmentList.splice(uploadingIndex, 1);
        }
      }
    },
    handleUploadProgress(event, file, fileList) {
      const index = this.attachmentList.findIndex(item => item.uploading && item.file_name === file.name);
      if (index !== -1) {
        this.$set(this.attachmentList[index], 'uploadProgress', Math.round(event.percent));
        this.$set(this.attachmentList[index], 'uploadStatus', '');
      }
    },
    handleUploadError(err, file, fileList) {
      this.$message.error('上传失败');
      const index = this.attachmentList.findIndex(item => item.uploading && item.file_name === file.name);
      if (index !== -1) {
        this.attachmentList.splice(index, 1);
      }
    },
    beforeUpload(file) {
      // 添加上传中的文件
      const attachment = {
        file_name: file.name,
        file_size: file.size,
        uploading: true,
        uploadProgress: 0,
        uploadStatus: ''
      };
      this.attachmentList.push(attachment);
      return true;
    },
    cancelUpload(index) {
      // 取消上传
      if (this.$refs.upload) {
        this.$refs.upload.abort();
      }
      this.attachmentList.splice(index, 1);
      this.$message.info('已取消上传');
    },
    removeAttachment(index) {
      this.$confirm('确定要删除该附件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const attachment = this.attachmentList[index];
        if (attachment.id) {
          // 如果有ID，调用删除接口
          this.axios.post('/manage/Attachment/delete', { id: attachment.id })
            .then((res) => {
              if (res) {
                this.attachmentList.splice(index, 1);
                this.$message.success('删除成功');
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          // 如果没有ID，直接移除
          this.attachmentList.splice(index, 1);
        }
      }).catch(() => {});
    },
    getFileIcon(fileName) {
      const ext = fileName.split('.').pop().toLowerCase();
      if (ext === 'pdf') {
        return 'el-icon-document';
      } else if (['doc', 'docx'].includes(ext)) {
        return 'el-icon-document';
      } else if (['xls', 'xlsx'].includes(ext)) {
        return 'el-icon-document';
      } else {
        return 'el-icon-document';
      }
    },
    getFileIconColor(fileName) {
      const ext = fileName.split('.').pop().toLowerCase();
      if (ext === 'pdf') {
        return '#F56C6C';
      } else if (['doc', 'docx'].includes(ext)) {
        return '#409EFF';
      } else if (['xls', 'xlsx'].includes(ext)) {
        return '#67C23A';
      } else {
        return '#909399';
      }
    },
    formatFileSize(size) {
      if (!size) return '0B';
      const unit = ['B', 'KB', 'MB', 'GB'];
      let index = 0;
      while (size >= 1024 && index < unit.length - 1) {
        size = size / 1024;
        index++;
      }
      return size.toFixed(1) + unit[index];
    },
    /** 保存项目 */
    handleSave() {
      const _this = this;
      // 表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          this.is_ajax = true;
          // 构建提交数据
          let _data = {
            id: this.form.id || '',
            title: this.form.title || '',
            begin_time: this.form.begin_time || '',
            end_time: this.form.end_time || '',
            pw_df_begin_time: this.form.pw_df_begin_time || '',
            pw_df_end_time: this.form.pw_df_end_time || '',
            base_score_rate: this.form.base_weight !== null && this.form.base_weight !== undefined ? this.form.base_weight : (this.form.base_score_rate || ''),
            pw_score_rate: this.form.judge_weight !== null && this.form.judge_weight !== undefined ? this.form.judge_weight : (this.form.pw_score_rate || ''),
            q_id: this.form.question_template_id || this.form.q_id || '',
            content: this.form.description || this.form.content || '',
            kouling: this.form.kouling || '',
            // 处理附件ID数组
            arrr_data: this.attachmentList.filter(item => !item.uploading && item.id).map(item => item.id)
          };
          
          // 使用项目API创建或更新项目
          projectApi.createOrUpdate(_data).then(function (res) {
            if (res) {
              _this.$message.success('保存成功');
              // 如果保存成功且有返回ID，更新当前ID
              if (res.data && res.data.id) {
                _this.id = res.data.id;
                _this.form.id = res.data.id;
                // 更新URL中的ID
                _this.$router.replace({
                  path: '/project/edit',
                  query: { id: res.data.id }
                });
              }
              // 重新获取项目详情，确保数据同步
              _this.getData();
            } else {
              _this.$message.error(res.message || '保存失败');
            }
            _this.is_ajax = false;
          }).catch(function (error) {
            console.error('保存项目失败:', error);
            _this.$message.error('保存失败，请重试');
            _this.is_ajax = false;
          });
        } else {
          this.$message.warning('请完善表单信息');
        }
      });
    },
  }
}
</script>

<style scoped>
.form_section {
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 20px;
}

.section_title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.attachment_list {
  min-height: 50px;
}

.attachment_item {
  padding: 10px;
  background: #F5F7FA;
  border-radius: 4px;
  border: 1px solid #EBEEF5;
}

.file_icon {
  font-size: 24px;
}

.file_name {
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file_size {
  font-size: 12px;
  color: #909399;
}

.bottom_actions {
  text-align: right;
  padding: 20px 0;
  border-top: 1px solid #EBEEF5;
}

.bottom_actions .el-button {
  margin-left: 10px;
}
</style>
